package com.liang.liangrpceasy.service;

import com.liang.liangrpceasy.model.RpcRequest;
import com.liang.liangrpceasy.model.RpcResponse;
import com.liang.liangrpceasy.register.LocalRegister;
import com.liang.liangrpceasy.serializer.JdkSerializer;
import com.liang.liangrpceasy.serializer.Serializer;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import java.lang.reflect.Method;

/**
 * Http 请求处理
 */
public class HttpServiceHandler implements Handler<HttpServerRequest> {
    @Override
    public void handle(HttpServerRequest request) {
        // 指定指定序列化器
        final Serializer serializer = new JdkSerializer();
        // 记录日志
        System.out.println("请求地址：" + request.method() + " " + request.uri());
        // 异步处理HTTP请求
        request.bodyHandler(body -> {
            byte[] bytes = body.getBytes();
            RpcRequest rpcRequest = null;
            try {
                rpcRequest = serializer.deserialize(bytes, RpcRequest.class);
            }catch (Exception e) {
                e.printStackTrace();
            }

            // 构造响应结果对象
            RpcResponse rpcResponse = new RpcResponse();

            if (rpcResponse == null){
                rpcResponse.setMessage("请求为空");
                doResponse(request, rpcResponse,serializer);
                return;
            }

            try {
                Class<?> implClass = LocalRegister.getService(rpcRequest.getServiceName());
                Method method = implClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
                Object result = method.invoke(implClass.newInstance(),rpcRequest.getArgs());
                // 封装返回结果
                rpcResponse.setData(result);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMessage("ok");
            } catch (Exception e) {
                e.printStackTrace();
                rpcResponse.setMessage(e.getMessage());
                rpcResponse.setException(e);
            }

            // 响应
            doResponse(request, rpcResponse,serializer);
        });

    }

    /**
     * 响应结果
     * @param request 请求
     * @param rpcResponse 响应
     * @param serializer 序列化器
     */
    void doResponse(HttpServerRequest request, RpcResponse rpcResponse, Serializer serializer) {
        HttpServerResponse httpServerResponse = request.response()
                .putHeader("content-type","application/json");
        try {
            byte[] serialize = serializer.serialize(rpcResponse);
            httpServerResponse.end(Buffer.buffer(serialize));
        } catch (Exception e) {
            e.printStackTrace();
            httpServerResponse.end(Buffer.buffer());
        }

    }
}
